package com.lm.aspectj.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class LoggingAspect {

    // 定义切点：拦截 controller 包下所有方法
    @Pointcut("execution(* com.lm.aspectj.controller..*(..))")
    public void controllerMethods() {}

    // 方法执行前
    @Before("controllerMethods()")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("👉 调用方法：" + joinPoint.getSignature().toShortString() +
                " 参数：" + Arrays.toString(joinPoint.getArgs()));
    }

    // 方法执行后
    @After("controllerMethods()")
    public void logAfter(JoinPoint joinPoint) {
        System.out.println("✅ 方法执行结束：" + joinPoint.getSignature().toShortString());
    }

    // 方法返回后
    @AfterReturning(value = "controllerMethods()", returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {
        System.out.println("🔙 方法返回值：" + result);
    }

    // 方法抛出异常
    @AfterThrowing(value = "controllerMethods()", throwing = "ex")
    public void logAfterThrowing(JoinPoint joinPoint, Exception ex) {
        System.out.println("❌ 方法异常：" + joinPoint.getSignature().toShortString() +
                " 异常信息：" + ex.getMessage());
    }
}
